import Ember from 'ember';
import FormState from 'emberworkspace/utils/form-state';
import csrfGetter from 'emberworkspace/utils/csrf-getter';

export default Ember.Controller.extend({
  pageTitle: "登陆系统",
  pageSubTitle: "可以使用用户名、邮箱或者手机号登陆",
  username: "",
  password: "",
  formState: FormState.create(),
  afterLogin(data) {
    var userState = this.get('userState'),
      myGlobals = this.get('myGlobals'),
      store = this.get('store'),
      previousTransition = this.get('previousTransition');

    userState.initMe(store, myGlobals, data.userState);
    // Log the user in, then reattempt previous transition if it exists.
    if (previousTransition) {
      this.set('previousTransition', null);
      previousTransition.retry();
    } else {
      // Default back to homepage
      this.transitionToRoute('index');
    }

  },
  actions: {
    submitForm: function() {
      var headers = csrfGetter(),
        self = this,
        store = this.get('store'),
        data = {
          username: this.get('username'),
          password: this.get('password')
        };

      var formState = this.get('formState');

      if (!data.username || !data.password) {
        formState.setError({
          fn: "",
          msg: "请输入用户名和密码"
        });
        return;
      }
      formState.startSaving();
      return Ember.$.ajax({
          // url: "/login/do?success=true",
          url: "/login/do",
          contentType: "application/json; charset=UTF-8",
          context: this,
          data: JSON.stringify(data),
          headers: headers,
          method: "POST",
          statusCode: {
            404: function() {
              alert("page not found");
            }
          },
        })
        .done(function(data, textStatus, jqXHR) {
          if (data.message === "NO_MESSAGE") { //success
            formState.success();
            self.afterLogin(data);
          } else {
            formState.setError({
              fn: "",
              msg: "用户名或密码错误！"
            });
          }
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
          formState.setError({
            fn: "",
            msg: "服务器返回错误代码。"
          });
        });
    }
  }
});
